package com.ztz.mynewdemo.fragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.ztz.mynewdemo.R;
import com.ztz.mynewdemo.activity.LocateActivity;
import com.ztz.mynewdemo.activity.WeatherActivityTwo;
import com.ztz.mynewdemo.bean.PersonInfoResponse;
import com.ztz.mynewdemo.bean.WeatherResponse;
import com.ztz.mynewdemo.utils.AppConfigUtils;
import com.ztz.mynewdemo.utils.GlideCircleTransform;
import com.ztz.mynewdemo.utils.NewsApi;
import com.ztz.mynewdemo.utils.OkHttpUtils;
import com.ztz.mynewdemo.utils.RequestUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;

/**
 * Created by wqewqe on 2018/1/4.
 */

public class UseInfoFragment extends DialogFragment {
    private static final String TAG = "UseInfoFragment";
    public static final String LONGITUDE = "longitude";
    public static final String LATITUDE = "latitude";
    TextView tv_weather, tv_name;
    TextView tv_detail, tv_city;
    List<WeatherResponse.ResultBean.TodayBean> todayBeanList = new ArrayList<>();
    ImageView ivPic;

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_userinfo, null);
        builder.setView(view);
        Bundle bundle = getArguments();
        tv_name = (TextView) view.findViewById(R.id.tv_name);
        tv_weather = (TextView) view.findViewById(R.id.tv_weather);
        tv_detail = (TextView) view.findViewById(R.id.weather_detail);
        tv_city = (TextView) view.findViewById(R.id.tv_city);
        ivPic=(ImageView)view.findViewById(R.id.iv_pic);
        final double longitude = bundle.getDouble(LocateActivity.LONGITUDE);
        final double latitude = bundle.getDouble(LocateActivity.LATITUDE);
        tv_detail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), WeatherActivityTwo.class);
                intent.putExtra(LONGITUDE, longitude);
                intent.putExtra(LATITUDE, latitude);
                getActivity().startActivity(intent);
            }
        });
        tv_name.setText(AVUser.getCurrentUser().getUsername());
//        getUserInfo();
        updatePic();
        getData(latitude, longitude);
        return builder.create();
    }
    public void updatePic()
    {
        AVQuery<AVObject> query=new AVQuery<>("Todo");
        query.orderByAscending("createAt");
        query.include("owner");
        query.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> list, AVException e) {
                if(list.size()-1>=0) {
                    String url = list.get(list.size() - 1).getAVFile("images").getUrl();
                    if (url != null) {
                        Glide.with(getActivity())
                                .load(url)
                                .centerCrop()
                                .transform(new GlideCircleTransform(getActivity()))
                                .into(ivPic);
                    }
                }
            }
        });
    }
    public void getUserInfo() {
        OkHttpClient client = OkHttpUtils.getOkHttpClient();
        client.newCall(RequestUtils.requestGET(NewsApi.URL._User + AppConfigUtils.getInstance().getLoginInfo(getActivity()).getObjectId()))
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, okhttp3.Response response) throws IOException {
                        String result = response.body().string();
                        final PersonInfoResponse personInfo = new Gson().fromJson(result, PersonInfoResponse.class);
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tv_name.setText(personInfo.getUsername() + "");
                            }
                        });
                    }
                });
    }

    private void getData(double latitude, double longitude) {
        OkGo.<String>get(NewsApi.GEO)
                .tag(this)
                .params("lon", longitude)
                .params("lat", latitude)
                .params("format", 2)
                .params("dtype", "json")
                .params("key", "60f7fc28a4b0e9e8816813b2db7ed5f0")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String s = response.body();
                        Gson gson = new Gson();
                        WeatherResponse weatherResponse = gson.fromJson(s, WeatherResponse.class);
                        todayBeanList.add(weatherResponse.getResult().getToday());
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tv_city.setText(todayBeanList.get(0).getCity());
                                tv_weather.setText(todayBeanList.get(0).getWeather());
                            }
                        });
                        Log.i(TAG, "onSuccess: " + s);
                    }
                });
    }

}
